package controller

import (
	"errors"
	"github.com/cy77cc/hioshop/global"
	"github.com/cy77cc/hioshop/models"
	"github.com/cy77cc/hioshop/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"time"
)

type AuthHandler struct {
}

type login struct {
	Code string `json:"code" form:"code"`
}

func (a *AuthHandler) LoginByWeixin(ctx *gin.Context) {
	loginForm := login{}
	res := utils.NewResponse()
	ctx.ShouldBind(&loginForm)
	//var currentTime = time.Now().Unix() / 1000
	//var clientIP = ctx.ClientIP()
	var isNew int8

	appid := ctx.GetString("appid")
	secret := ctx.GetString("secret")

	weixinRes := utils.WeixinResponse{}
	err := weixinRes.GetWeixinOpenid(loginForm.Code, appid, secret)
	if err != nil {
		res.SetRes(1, "error", err)
		ctx.JSON(http.StatusOK, res)
		return
	}

	if weixinRes.OpenId == "" {
		res.SetRes(1, "登录失败,openid无效", err)
		ctx.JSON(http.StatusOK, res)
		return
	}

	user := models.User{}
	user.WeixinOpenid = weixinRes.OpenId
	err = user.GetUserInfoByOpenId()
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		user.Username = "微信用户" + time.Now().Format("2006-01-02")
		user.Password = weixinRes.OpenId
		user.RegisterTime = time.Now()
		user.RegisterIp = 0
		user.LastLoginTime = time.Now()
		user.LastLoginIp = 0
		user.Mobile = ""
		user.WeixinOpenid = weixinRes.OpenId
		user.Nickname = "xx"
		user.Avatar = "/static/images/default_avatar.png"
		err := user.Create()
		if err != nil {
			res.SetRes(1, "注册失败", err)
			ctx.JSON(http.StatusOK, res)
			return
		}
		isNew = 1
	} else {
		user.LastLoginTime = time.Now()
		err := user.UpdateUserInfo()
		if err != nil {
			res.SetRes(1, "用户信息更新失败", err)
			ctx.JSON(http.StatusOK, res)
			return
		}
		isNew = 0
	}

	token, _ := utils.GenToken(user.ID)
	type resUser struct {
		Id       uint   `json:"id"`
		Username string `json:"username"`
		Nickname string `json:"nickname"`
		Avatar   string `json:"avatar"`
	}

	data := map[string]any{}
	data["token"] = token
	data["userInfo"] = resUser{
		Id:       user.ID,
		Username: user.Username,
		Nickname: user.Nickname,
		Avatar:   user.Avatar,
	}
	data["is_new"] = isNew
	res.SetRes(0, "success", data)
	ctx.JSON(http.StatusOK, res)
}

func (*AuthHandler) Register(ctx *gin.Context) {
	admin := models.Admin{}
	username := ctx.PostForm("username")
	password := ctx.PostForm("password")
	res := utils.NewResponse()

	if username == "" && password == "" {
		res.SetRes(1, "请求参数有误", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	admin.Username = username
	admin.PasswordSalt = global.CONFIG.System.SecretKey
	admin.Password = utils.GetMD5SUM(password, admin.PasswordSalt)
	err := admin.Create()
	if err != nil {
		res.SetRes(1, "创建用户失败", err)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	ctx.JSON(http.StatusOK, res)
}

func (*AuthHandler) Login(ctx *gin.Context) {
	res := utils.NewResponse()
	admin := models.Admin{}
	if err := ctx.ShouldBindJSON(&admin); err != nil {
		res.SetRes(1, "请求参数错误", err)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	password := admin.Password
	err := admin.GetAdminByName()
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		res.SetRes(1, "用户不存在", err)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	if utils.GetMD5SUM(password, admin.PasswordSalt) != admin.Password {
		res.SetRes(1, "密码错误", err)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	admin.LastLoginTime = int(time.Now().Unix())
	admin.LastLoginIp = ctx.ClientIP()

	err = admin.UpdateLoginInfo()
	if err != nil {
		res.SetRes(1, "更新登录信息失败", err)
		ctx.JSON(http.StatusForbidden, res)
		return
	}

	token, err := utils.GenToken(admin.ID)
	if err != nil {
		res.SetRes(1, "token生成失败", err)
		ctx.JSON(http.StatusForbidden, res)
		return
	}

	res.SetRes(0, "success", map[string]any{
		"token": token,
	})

	ctx.JSON(http.StatusOK, res)

}
